/*********************
 *      INCLUDES
 *********************/
#include <rtthread.h>
#include <rtdevice.h>
#include "littlevgl2rtt.h"
#include "lvgl.h"
#include "lvsf_comp.h"
#include "gui_app_fwk.h"
#include "lv_ext_resource_manager.h"
#include "lv_ex_data.h"
#include "app_mem.h"
#include <stdlib.h>
#include <time.h>
#include "math.h"
#include "step_service.h"  // 添加步数服务头文件

// 传感器相关头文件
#include "sensor_liteon_ltr303.h"
#include "st_lsm6dsl_sensor_v1.h"
#include "sensor_manager.h"

/*********************
 *      字体定义
 *********************/
#ifndef FONT_MIDL
#define FONT_MIDL LV_FONT_DEFAULT
#endif

/*********************
 *      记步器数据结构
 *********************/
typedef struct {
    uint32_t step_count;          // 总步数
    uint32_t daily_goal;          // 每日目标步数
    uint32_t calories;            // 消耗卡路里
    float distance;               // 行走距离(公里)
    uint8_t is_running;           // 是否正在计步
} pedometer_data_t;

static pedometer_data_t pedometer = {
    .step_count = 0,
    .daily_goal = 10000,
    .calories = 0,
    .distance = 0.0f,
    .is_running = 1  // 默认开启状态
};

/*********************
 *      UI控件指针
 *********************/
static lv_obj_t *step_label;    
static lv_obj_t *goal_label;
static lv_obj_t *calorie_label;
static lv_obj_t *distance_label;
static lv_obj_t *progress_bar;
static lv_obj_t *start_stop_btn;
static lv_obj_t *status_label;
static lv_timer_t *step_ui_timer = NULL; // 新增: 周期刷新UI的定时器

// 前置声明，避免在 on_step_update 中出现隐式声明导致与后面 static 定义冲突
static void update_ui_display(void);

/*********************
 *      更新UI显示
 *********************/
void on_step_update(uint32_t steps, uint32_t calories, float distance) {
    // 直接更新内部数据并统一刷新UI，避免未定义的辅助函数
    pedometer.step_count = steps;
    pedometer.calories = calories;
    pedometer.distance = distance;
    update_ui_display();
}
static void update_ui_display(void)
{
    // 从服务获取最新数据
    uint32_t current_steps, current_calories;
    float current_distance;
    
    if (step_service_get_data(&current_steps, &current_calories, &current_distance) == 0) {
        pedometer.step_count = current_steps;
        pedometer.calories = current_calories;
        pedometer.distance = current_distance;
    }
    
    lv_label_set_text_fmt(step_label, "%d", pedometer.step_count);
    lv_label_set_text_fmt(goal_label, "目标: %d/%d", pedometer.step_count, pedometer.daily_goal);
    lv_label_set_text_fmt(calorie_label, "卡路里: %d cal", pedometer.calories);
    lv_label_set_text_fmt(distance_label, "距离: %.2f km", pedometer.distance);
    
    // 更新进度条
    int progress = 0;
    if (pedometer.daily_goal > 0) {
        progress = (pedometer.step_count * 100) / pedometer.daily_goal;
        if (progress > 100) progress = 100;
        if (progress < 0) progress = 0;
    }
    lv_bar_set_value(progress_bar, progress, LV_ANIM_ON);
    
    // 根据进度改变颜色
    if (progress < 50) {
        lv_obj_set_style_bg_color(progress_bar, lv_color_hex(0x00FF00), LV_PART_INDICATOR);
    } else if (progress < 80) {
        lv_obj_set_style_bg_color(progress_bar, lv_color_hex(0xFFFF00), LV_PART_INDICATOR);
    } else {
        lv_obj_set_style_bg_color(progress_bar, lv_color_hex(0xFF0000), LV_PART_INDICATOR);
    }
    
    // 更新状态显示
    if (pedometer.is_running) {
        lv_label_set_text(status_label, "状态: 开启");
        lv_obj_set_style_text_color(status_label, lv_color_hex(0x00FF00), 0);
    } else {
        lv_label_set_text(status_label, "状态: 关闭");
        lv_obj_set_style_text_color(status_label, lv_color_hex(0xFF0000), 0);
    }
}

/*********************
 *      定时器回调：实时刷新步数显示
 *********************/
static void step_timer_cb(lv_timer_t *timer)
{
    (void)timer;
    if (pedometer.is_running) {
        // 周期性从服务读取最新数据并刷新UI
        update_ui_display();
    }
}

/*********************
 *      事件处理函数
 *********************/

// 开启/关闭记步
static void start_stop_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED) {
        pedometer.is_running = !pedometer.is_running;
        
        // 设置服务激活状态
        step_service_set_active(pedometer.is_running);
        
        if (pedometer.is_running) {
            lv_obj_set_style_bg_color(start_stop_btn, lv_color_hex(0xFF0000), 0);
            lv_label_set_text(lv_obj_get_child(start_stop_btn, 0), "关闭");
        } else {
            lv_obj_set_style_bg_color(start_stop_btn, lv_color_hex(0x00FF00), 0);
            lv_label_set_text(lv_obj_get_child(start_stop_btn, 0), "开启");
        }
        
        update_ui_display();
    }
}

// 重置步数
static void reset_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED) {
        step_service_reset();
        update_ui_display();
    }
}

// 设置目标步数
static void set_goal_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED) {
        // 这里可以添加设置目标步数的对话框
        // 暂时使用固定值10000
        pedometer.daily_goal = 10000;
        step_service_set_goal(10000);
        update_ui_display();
    }
}

/*********************
 *      UI创建函数
 *********************/
static void create_pedometer_ui(lv_obj_t *parent)
{
    // 创建主容器
    lv_obj_t *cont = lv_obj_create(parent);
    // 使用运行时获取的分辨率（避免未定义的 LV_HOR_RES_MAX / LV_VER_RES_MAX）
    lv_coord_t disp_w = lv_disp_get_hor_res(NULL);
    lv_coord_t disp_h = lv_disp_get_ver_res(NULL);
    lv_obj_set_size(cont, disp_w, disp_h);
    lv_obj_set_style_bg_color(cont, lv_color_hex(0x000000), 0);
    lv_obj_set_style_border_width(cont, 0, 0);
    
    // 状态标签
    status_label = lv_label_create(cont);
    lv_label_set_text(status_label, "状态: 开启");
    lv_obj_set_style_text_color(status_label, lv_color_hex(0x00FF00), 0);
    lv_obj_align(status_label, LV_ALIGN_TOP_LEFT, 20, 20);
    
    // 步数显示（大字体）
    step_label = lv_label_create(cont);
    lv_label_set_text_fmt(step_label, "%d", pedometer.step_count);
    lv_obj_set_style_text_color(step_label, LV_COLOR_WHITE, 0);
    lv_obj_align(step_label, LV_ALIGN_TOP_MID, 0, 50);
    
    // 步数单位标签
    lv_obj_t *steps_text = lv_label_create(cont);
    lv_label_set_text(steps_text, "步数");
    lv_obj_set_style_text_color(steps_text, LV_COLOR_WHITE, 0);
    lv_obj_align_to(steps_text, step_label, LV_ALIGN_OUT_BOTTOM_MID, 0, 10);
    
    // 目标进度标签
    goal_label = lv_label_create(cont);
    lv_label_set_text_fmt(goal_label, "目标: %d/%d", pedometer.step_count, pedometer.daily_goal);
    lv_obj_set_style_text_color(goal_label, LV_COLOR_WHITE, 0);
    lv_obj_align_to(goal_label, steps_text, LV_ALIGN_OUT_BOTTOM_MID, 0, 20);
    
    // 进度条
    progress_bar = lv_bar_create(cont);
    lv_obj_set_size(progress_bar, 200, 20);
    lv_obj_align_to(progress_bar, goal_label, LV_ALIGN_OUT_BOTTOM_MID, 0, 15);
    lv_bar_set_range(progress_bar, 0, 100);
    lv_bar_set_value(progress_bar, 0, LV_ANIM_OFF);
    lv_obj_set_style_bg_color(progress_bar, lv_color_hex(0x444444), LV_PART_MAIN);
    lv_obj_set_style_bg_color(progress_bar, lv_color_hex(0x00FF00), LV_PART_INDICATOR);
    
    // 卡路里标签
    calorie_label = lv_label_create(cont);
    lv_label_set_text_fmt(calorie_label, "卡路里: %d cal", pedometer.calories);
    lv_obj_set_style_text_color(calorie_label, LV_COLOR_WHITE, 0);
    lv_obj_align_to(calorie_label, progress_bar, LV_ALIGN_OUT_BOTTOM_MID, 0, 20);
    
    // 距离标签
    distance_label = lv_label_create(cont);
    lv_label_set_text_fmt(distance_label, "距离: %.2f km", pedometer.distance);
    lv_obj_set_style_text_color(distance_label, LV_COLOR_WHITE, 0);
    lv_obj_align_to(distance_label, calorie_label, LV_ALIGN_OUT_BOTTOM_MID, 0, 10);
    
    // 按钮容器
    lv_obj_t *btn_cont = lv_obj_create(cont);
    lv_obj_set_size(btn_cont, 220, 60);
    lv_obj_align_to(btn_cont, distance_label, LV_ALIGN_OUT_BOTTOM_MID, 0, 30);
    lv_obj_set_style_bg_opa(btn_cont, LV_OPA_0, 0);
    lv_obj_set_style_border_width(btn_cont, 0, 0);
    
    // 开启/关闭按钮 - 初始状态为开启（红色）
    start_stop_btn = lv_btn_create(btn_cont);
    lv_obj_set_size(start_stop_btn, 100, 40);
    lv_obj_align(start_stop_btn, LV_ALIGN_LEFT_MID, 0, 0);
    lv_obj_set_style_bg_color(start_stop_btn, lv_color_hex(0xFF0000), 0); // 红色表示开启
    lv_obj_add_event_cb(start_stop_btn, start_stop_handler, LV_EVENT_CLICKED, NULL);
    
    lv_obj_t *btn_label = lv_label_create(start_stop_btn);
    lv_label_set_text(btn_label, "关闭"); // 按钮显示"关闭"，因为当前是开启状态
    lv_obj_center(btn_label);
    
    // 重置按钮
    lv_obj_t *reset_btn = lv_btn_create(btn_cont);
    lv_obj_set_size(reset_btn, 100, 40);
    lv_obj_align(reset_btn, LV_ALIGN_RIGHT_MID, 0, 0);
    lv_obj_set_style_bg_color(reset_btn, lv_color_hex(0x555555), 0);
    lv_obj_add_event_cb(reset_btn, reset_handler, LV_EVENT_CLICKED, NULL);
    
    lv_obj_t *reset_label = lv_label_create(reset_btn);
    lv_label_set_text(reset_label, "重置");
    lv_obj_center(reset_label);
}

/*********************
 *      应用生命周期
 *********************/
/*********************
 *      应用生命周期
 *********************/
static void on_start(void)
{
    // 创建记步器UI
    create_pedometer_ui(lv_scr_act());
    
    // 初始化显示数据
    step_service_get_data(&pedometer.step_count, &pedometer.calories, &pedometer.distance);
    
    // 获取步数服务的实际状态
    uint8_t service_active = 1;
    step_service_get_active_status(&service_active);
    
    // 同步UI状态到服务的实际状态
    pedometer.is_running = service_active;
    
    // 根据实际状态更新按钮显示
    if (pedometer.is_running) {
        lv_obj_set_style_bg_color(start_stop_btn, lv_color_hex(0xFF0000), 0);
        lv_label_set_text(lv_obj_get_child(start_stop_btn, 0), "关闭");
        lv_label_set_text(status_label, "状态: 开启");
        lv_obj_set_style_text_color(status_label, lv_color_hex(0x00FF00), 0);
    } else {
        lv_obj_set_style_bg_color(start_stop_btn, lv_color_hex(0x00FF00), 0);
        lv_label_set_text(lv_obj_get_child(start_stop_btn, 0), "开启");
        lv_label_set_text(status_label, "状态: 关闭");
        lv_obj_set_style_text_color(status_label, lv_color_hex(0xFF0000), 0);
    }
    
    update_ui_display();
    
    lv_img_cache_invalidate_src(NULL);

    // 创建定时器：每 1000ms 刷新一次界面，保证运动中实时显示步数
    if (step_ui_timer == NULL) {
        step_ui_timer = lv_timer_create(step_timer_cb, 1000, NULL);
    }
}

static void on_pause(void)
{
    // 不需要停止步数检测，服务在后台继续运行
    // 只更新UI状态
    update_ui_display();
}

static void on_resume(void)
{
    // 更新显示数据
    step_service_get_data(&pedometer.step_count, &pedometer.calories, &pedometer.distance);
    
    // 重新获取服务状态并同步UI
    uint8_t service_active = 1;
    step_service_get_active_status(&service_active);
    
    // 只有当状态发生变化时才更新UI
    if (pedometer.is_running != service_active) {
        pedometer.is_running = service_active;
        
        if (pedometer.is_running) {
            lv_obj_set_style_bg_color(start_stop_btn, lv_color_hex(0xFF0000), 0);
            lv_label_set_text(lv_obj_get_child(start_stop_btn, 0), "关闭");
            lv_label_set_text(status_label, "状态: 开启");
            lv_obj_set_style_text_color(status_label, lv_color_hex(0x00FF00), 0);
        } else {
            lv_obj_set_style_bg_color(start_stop_btn, lv_color_hex(0x00FF00), 0);
            lv_label_set_text(lv_obj_get_child(start_stop_btn, 0), "开启");
            lv_label_set_text(status_label, "状态: 关闭");
            lv_obj_set_style_text_color(status_label, lv_color_hex(0xFF0000), 0);
        }
    }
    
    update_ui_display();
}

static void on_stop(void)
{
    // 不需要关闭传感器，服务在后台继续运行
    // 只更新UI状态
    update_ui_display();

    // （可选）应用停止时删除定时器，避免资源占用；若希望后台继续刷新可移除此段
    if (step_ui_timer) {
        lv_timer_del(step_ui_timer);
        step_ui_timer = NULL;
    }
}

static void msg_handler(gui_app_msg_type_t msg, void *param)
{
    switch (msg)
    {
        case GUI_APP_MSG_ONSTART:
            on_start();
            break;

        case GUI_APP_MSG_ONRESUME:
            on_resume();
            break;

        case GUI_APP_MSG_ONPAUSE:
            on_pause();
            break;

        case GUI_APP_MSG_ONSTOP:
            on_stop();
            break;
        default:
            break;
    }
}

LV_IMG_DECLARE(img_workout);
#define APP_ID "pedometer"

static int app_main(intent_t i)
{
    gui_app_regist_msg_handler(APP_ID, msg_handler);
    return 0;
}

BUILTIN_APP_EXPORT(LV_EXT_STR_ID(lckfb), LV_EXT_IMG_GET(img_workout), APP_ID, app_main);